import time
from datetime import datetime,timedelta
from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Category
from info.utils.common import user_data_info
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu

# @admin_blu.before_request
# def admin_user():
#     is_admin = session.get("is_admin")
#     # 不是管理员  并且访问的路径不是/admin/index
#     if not is_admin and not request.method.endswith(url_for("admin.index")):
#         return render_template("news/index.html")

@admin_blu.route("/news_type",methods = ["POST","GET"])
def news_type():
    """新闻标题分类"""
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno = RET.NODATA ,errmsg = "未查询到数据")
        category_list = []
        for category in categories:
            category_list.append(category)
        # 删除最新的分类
        category_list.pop(0)

        data = {
            "categories":category_list
        }
        return render_template("admin/news_type.html",data = data)

    try:
         cname = request.json.get("name")
         cid = request.json.get("id")
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    if not cname:
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误")
    if cid:
#         有分类id代表查询相关数据
        try:
            cid = int(cid)
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno = RET.PARAMERR ,errmsg = "参数错误")
        if not category:
            return jsonify(errno = RET.NODATA ,errmsg = "未查询到数据")
        category.name = cname
    else:
        category = Category()
        category.name = cname
        db.session.add(category)
    return jsonify(errno = RET.OK ,errmsg = "OK")


@admin_blu.route("/news_edit_action",methods = ["POST"])
def news_edit_action():
    """版式编辑点击确认后跳转页面"""
    # 新闻id
    news_id = request.form.get("news_id")
    # 新闻主题
    title = request.form.get("title")
    # 新闻内容
    content = request.form.get("content")
    # 上传图片
    file_img = request.files.get("file_img")
    # 新闻分类
    category_id = request.form.get("category_id")
    # 新闻摘要
    digest = request.form.get("digest")

    if not all([title,content,category_id,digest]):
        return jsonify(errno = RET.DATAERR ,errmsg = "参数错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "未查询到数据")
    # 如果有图片
    if file_img:
        # 将图片读取出来
        try:
            files_img = file_img.read()
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno = RET.DATAERR ,errmsg = "图片读取失败")

        # 上传到七牛云
        try:
            key = storage(files_img)
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno = RET.PARAMERR ,errmsg = "上传失败")
        # 保存到数据库--拼接好路径
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    # 修改数据库数据
    try:
        news.title = title
        news.category_id = category_id
        news.content = content
        news.digest = digest
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "数据修改失败")

    return jsonify(errno = RET.OK ,errmsg = "OK")

@admin_blu.route("/news_edit_detail")
def news_edit_detail():
    """
    新闻的版本编辑详情页
    :return:
    """
    news_id = request.args.get("news_id")
    if not news_id:
        abort(404)
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "查询错误")

    if not news:
        return jsonify(errno = RET.DBERR ,errmsg = "未查询到数据")
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.errno(e)
        return render_template("admin/news_edit_detail.html",errmsg = "数据查询错误")
    print(news.category_id)

    category_list = []
    for category in categories:
        # 取到分类的字典
        cate_dict = category.to_dict()
        # 判断当前遍历的分类是否是当前新闻的分类
        if category.id == news.category_id:
            # 增加一个属性来表示是否是当前新闻的分类
            cate_dict["is_selected"] = True
        category_list.append(cate_dict)
    # 移除最新的分类
    category_list.pop(0)
    data = {
        "news":news.to_dict(),
        "categories":category_list
    }
    return render_template("admin/news_edit_detail.html",data = data)



@admin_blu.route("/news_edit")
def news_edit():
    """
    新闻管理--新闻版式编辑主页
    :return:
    """
    page = request.args.get("p","1")
    keysword = request.args.get("keysword")
    if not page:
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    # 将条件装将一个列表中
    filter = [News.status == 0]
    # 判断有没有关键字搜索
    if keysword:
        filter.append(News.title.contains(keysword))
    try:
        # *filter将条件解包
        news_dict = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "未查询到数据")
    current_page = news_dict.page
    total_page = news_dict.pages
    news = news_dict.items
    news_list = []
    for new in news:
        news_list.append(new)

    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news_list":news_list,
        "content":keysword
    }

    return render_template("admin/news_edit.html",data = data)


@admin_blu.route("/news_review_action",methods = ["POST"])
def news_review_action():
    """
    新闻审核详情页
    :return:
    """
    action = request.json.get("action")
    news_id = request.json.get("news_id")

    if not all([news_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据错误")
    if not news:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    # try:
    #     categories = Category.query.all()
    # except Exception as e:
    #     current_app.logger.errno(e)
    #     return jsonify(errno = RET.DBERR,errmsg = "未查询到数据")
    #
    # category_list = []
    # for category in categories:
    #     category_list.append(category)

    if action == "accept":
         News.status = 0
    else:
        # 有数据代表不通过
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
        try:
            News.status = -1
            News.reason = reason
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    return jsonify(errno = RET.OK ,errmsg = "OK")


# news_id通过审核的跳转来传递过来
@admin_blu.route("/news_review_detail/<int:news_id>",methods= ["POST","GET"])
def news_review_detail(news_id):
    """
    管理界面--新闻管理>新闻审核
    :return:
    """
    # 通过id查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})
    try:
        category = Category.query.filter(Category.id == news.category_id).first()
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DBERR ,errmsg = "未查询到数据")

    # 返回数据
    data = {"news": news.to_dict(),
            "category":category
            }
    return render_template('admin/news_review_detail.html', data=data)


@admin_blu.route("/news_review")
def news_review():
    """
    管理界面--新闻管理
    :return:
    """
    page = request.args.get("p","1")
    keysword = request.args.get("keysword")
    if not page:
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    try:
        page = int(page)
    except Exception as e:
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    # 总页数
    total_page = 1
    # 当前页数
    current_page = 1

    filter_list = [News.status != 0]
    if keysword:
        filter_list.append(News.title.contains(keysword))
    try:
        news_dict = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR ,errmsg = "数据库查询错误")
    news = news_dict.items
    current_page = news_dict.page
    total_page = news_dict.pages

    news_list = []
    for new in news:
        news_list.append(new.to_review_dict())
    context = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list,
        "keysword":keysword
    }
    return render_template("admin/news_review.html", data = context)


@admin_blu.route("/user_list")
def user_list():
    """
    管理员--用户列表
    :return:
    """
    # 获取当前页数 --GET方式--通过url传递--request.args来获取
    page = request.args.get("page","1")
    if not page:
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")

    try:
        user = User.query.filter(User.is_admin == False).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR ,errmsg = "数据库查询错误")
    # 当前页
    user_page = user.page
    # 总页数
    total_pages = user.pages
    # 内容
    user_counts = user.items
    counts_list = []
    for count in user_counts:
        counts_list.append(count.to_admin_dict())
    data = {
        "users":counts_list,
        "total_page":total_pages,
        "current_page":user_page
    }
    return render_template("admin/user_list.html",data = data)


@admin_blu.route("/user_count")
def user_count():
    """
    用户统计
    :return:
    """
    # 总用户
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    mon_count = 0
    t = time.localtime()
    # print(t)
    begin_data = "%d-%02d-01" %(t.tm_year,t.tm_mon)
    # 月活跃用户
    begin_mon_date = datetime.strptime(begin_data,"%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.create_time > begin_mon_date,User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日活跃用户
    day_count = 0
    begin_day_date = "%d-%02d-%02d" %(t.tm_year,t.tm_mon,t.tm_mday)
    day_date = datetime.strptime(begin_day_date,"%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False,User.create_time>day_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 折线图
    # 每天的时间列表
    total_time = []
    # 每天的活跃人数
    total_people = []

    # 取到当前的数据字符串
    now_time = "%d-%02d-%02d" %(t.tm_year,t.tm_mon,t.tm_mday)
    # 将当前的时间字符串转化为时间对象--才能计算
    dotay_time = datetime.strptime(now_time,"%Y-%m-%d")

    for i in range(0,30):
        # 今天的初始化时间
        new_now_time = dotay_time - timedelta(days=i)
        # 今天后一天的初始化时间--相当于是今天的24点
        old_now_time = dotay_time - timedelta(days=(i-1))
        # 将时间对象转化为字符串对象
        now_time = new_now_time.strftime('%Y-%m-%d')
        total_time.append(now_time)
        # 找到当天的活跃人数  --今天的0:0:0--到 24点---相当于第2天的0点
        day_people_count = User.query.filter(User.create_time >= new_now_time,User.create_time <= old_now_time).count()
        total_people.append(day_people_count)

    data = {
        "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "total_people":total_people,
        "total_time":total_time
    }
    return render_template("admin/user_count.html",data = data)


@admin_blu.route("/login",methods = ["POST","GET"])
def login():
    """
    管理员--登陆界面
    :return:
    """
    if request.method == "GET":
        return render_template("admin/login.html")

    username = request.form.get("username")
    password = request.form.get("password")

    try:
        user = User.query.filter(User.mobile == username,User.is_admin == 1).first()
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno = RET.DATAERR ,errmsg = "不是管理员谢绝访问")

    if not user:
        return render_template("admin/login.html",errmsg = "请输入参数")

    if not all ([username,password]):
        return jsonify(errno = RET.DATAERR ,errmsg = "数据错误")

    if not user.check_password(password):
        return jsonify(errno = RET.DATAERR ,errmsg = "用户名或者密码不对")

    # 保存用户信息--保持会话
    session['mobile'] = user.mobile
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session["is_admin"] = user.is_admin

    return render_template("admin/index.html",user = user.to_dict())



@admin_blu.route("/index")
@user_data_info
def index():
    """
    管理员--主页
    :return:
    """
    user = g.user
    # print(user.id)
    return render_template("admin/index.html",user = user.to_dict())



